import loadingUrl from '@/assets/loading.svg'
import styles from './loading.module.less'
// 得到 loading 的 el 元素
const getLoadingEl = (el: HTMLElement) => {
  return el.querySelectorAll('img[data-role=loading]')
}

// 创建 loading 元素
const createLoadingEl = () => {
  const img = document.createElement('img')
  img.setAttribute('data-role', 'loading')
  img.src = loadingUrl
  img.className = styles['loading']
  return img
}

export default function (el: HTMLElement, binding: any) {
  const curImg = getLoadingEl(el)
  if (binding.value) {
    if (!curImg.length) {
      const img = createLoadingEl()
      el.appendChild(img)
    }
  } else {
    if (curImg) {
      curImg.forEach((img) => img.remove())
    }
  }
}
